package org.apache.cordova.LakalaPay;

import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import org.apache.cordova.BuildConfig;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * This class echoes a string called from JavaScript.
 */
public class LakalaPay extends CordovaPlugin {
  JSONObject mOrder;
  double mTotalSum;
  String mPayTp;
  String mTime;
  private static final String PACKAGENAME = "com.ionicframework.starter";
  private static final Map<String, String> payType;

  static {
    payType = new HashMap<String, String>();
    payType.put("0", "000000");
    payType.put("1", "660000");
  }

  @Override
  public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("payOrders")) {
      mOrder = args.getJSONObject(0);
      mTotalSum = args.getDouble(1);
      mPayTp = args.getString(2);
      this.payOrders(callbackContext);
      return true;
    }
    return false;
  }

  private void payOrders(CallbackContext callbackContext) {
    if (mOrder != null) {

      if (BuildConfig.DEBUG) {
        mTotalSum = 0.01;
        System.out.printf("debug environment\n");
      }
      String sOrderInfo = printOrder();
      System.out.printf("receive order: %s\n", sOrderInfo);
      String procCd = payType.get(mPayTp);
      Intent intent = new Intent();
      ComponentName component = new ComponentName(
        "com.lkl.cloudpos.payment",
        "com.lkl.cloudpos.payment.activity.MainMenuActivity");

      Bundle bundle = new Bundle();
      // 0200 请求　0210 应答
      bundle.putString("msg_tp", "0200");
      // 0 银行卡 1 表示扫码（扫码包括微信、支付宝、银联钱包）
      // TODO 需要在ui view上进行区分
      bundle.putString("pay_tp", mPayTp);
      // 000000 消费
      // 200000 消费撤销
      // 660000 扫码支付
      // 680000 扫码撤销
      // 700000 扫码补单
      // 900000 结算
      bundle.putString("proc_cd", procCd);
      // 00－消费类01-授权类
      bundle.putString("proc_tp", "00");
      // 金额
      bundle.putString("amt", Double.toString(mTotalSum));
      // 非必填第三方传入的订单号
      bundle.putString("order_no", "lessmore2015");
      // 调用者应用包名
      bundle.putString("appid", PACKAGENAME);
      mTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        .format(new Date());
      // 交易时间戳
      bundle.putString("time_stamp", mTime);
      bundle.putString("return_type", "1");
      // 订单信息-订单商品明细单价等
      bundle.putString("order_info", sOrderInfo);
      bundle.putString("print_info", sOrderInfo);
      intent.putExtras(bundle);

      intent.setComponent(component);
      cordova.startActivityForResult(this, intent, 0x01);

      callbackContext.success("");

    } else {
      callbackContext.error("order is empty.");
    }
  }

  public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    switch (resultCode) {
      // 交易成功
      case Activity.RESULT_OK:
        if (requestCode == 0x01) {
          // TODO 上传订单：
          uploadOrdersInfo();

          Bundle bundle = intent.getExtras();
          String detail = bundle.getString("txndetail");
          if (detail != null) {
            try {
              JSONObject jsonObject = new JSONObject(detail);
              // 商户号
              String merid = jsonObject.getString("merid");
              // 终端号
              String termid = jsonObject.getString("termid");
              // 批次号
              String batchno = jsonObject.getString("batchno");
              // 凭证号
              String systraceno = jsonObject.getString("systraceno");
              // 授权号
              String authcode = jsonObject.getString("authcode");
              // 扫码订单号
              String orderid_scan = jsonObject.getString("orderid_scan");

              ContentValues values = new ContentValues();
              values.put("merid", merid);
              values.put("termid", termid);
              values.put("batchno", batchno);
              values.put("systraceno", systraceno);
              values.put("authcode", authcode);
              values.put("orderid_scan", orderid_scan);
              values.put("pay_tp", mPayTp);
              values.put("time", mTime);
            } catch (JSONException e) {
              e.printStackTrace();
            }
          }
        }
        break;
      // 交易取消
      case Activity.RESULT_CANCELED:
        Bundle bundle = intent.getExtras();
        String reason = bundle.getString("reason");
        if (reason != null) {
          Toast.makeText(cordova.getActivity(), reason, Toast.LENGTH_SHORT).show();
        }
        break;
      // 交易失败
      case -2:
        bundle = intent.getExtras();
        reason = bundle.getString("reason");
        if (reason != null) {
          Toast.makeText(cordova.getActivity(), reason, Toast.LENGTH_SHORT).show();
        }
        break;
      default:
        break;
    }
  }

  private void uploadOrdersInfo() {
    System.out.printf("upload orders done!");
  }

  private String printOrder() {
    StringBuffer strBuf = new StringBuffer();
    JSONObject order;
    String info;
    try {
      strBuf.append("顾客：\t");
      strBuf.append(safeGetJson(mOrder, "CustomerName", ""));
      strBuf.append("\n");
      strBuf.append("电话：\t");
      strBuf.append(safeGetJson(mOrder, "CustomerTel", ""));
      strBuf.append("\n\n");
      JSONArray orders = mOrder.getJSONArray("Orders");
      int order_cnt = orders.length();
      for (int i = 0; i < order_cnt; i++) {
        order = orders.getJSONObject(i);
        strBuf.append("\t\t\t\t\t\t");
        strBuf.append(safeGetJson(order, "SuitType", "西服"));
        strBuf.append("\n");

        info = safeGetJson(order, "FabricBrand", "").toString();
        if (info.length() > 0) {
          strBuf.append("\t\t\t\t\t\t");
          strBuf.append(info);
          strBuf.append("\n");
        }
        info = safeGetJson(order, "FabricNumber", "").toString();
        if (info.length() > 0) {
          strBuf.append("\t\t\t\t\t\t");
          strBuf.append(info);
          strBuf.append("\n");
        }
        strBuf.append("单价：\t");
        strBuf.append(order.getDouble("Price"));
        strBuf.append("\n");

        strBuf.append("数量：\t");
        strBuf.append(order.getDouble("Count"));
        strBuf.append("\n");

        Double discount = order.getDouble("Discount");
        if (discount < 10) {
          strBuf.append("折扣：\t");
          strBuf.append(discount);
          strBuf.append("\n");
        }
        strBuf.append("=================== ******* ===================\n");
      }

    } catch (JSONException e) {
      e.printStackTrace();
    }
    return strBuf.toString();
  }

  private Object safeGetJson(JSONObject obj, String name, Object default_value) {
    Object v;
    try {
      v = obj.get(name);
    } catch (JSONException e) {
      v = default_value;
    }
    return v;
  }
}

